<?php
/**
 * Created by jinqiang on 2025/4/24 13:50.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Services\Om;


use App\Http\Models\Mysql\ExportOrderColourPositionTable;
use App\Http\Models\Mysql\ExportOrderCountTable;
use App\Http\Models\Mysql\ExportOrderItemTable;
use App\Http\Models\Mysql\ExportOrderProductColourTable;
use App\Http\Models\Mysql\ExportOrderProductSizeTable;
use App\Http\Models\Mysql\ExportOrderProductTable;
use App\Http\Models\Mysql\ExportOrderSizePositionTable;
use App\Http\Models\Mysql\ExportOrderTable;
use App\Http\Models\Mysql\Number2Table;
use App\Http\Models\Mysql\ProductSubcontractItemDetailCountTable;
use App\Http\Models\Mysql\ProductSubcontractItemTable;
use App\Http\Models\Mysql\SsyNewProductsSizeTable;
use App\Http\Models\Mysql\SsyStyleImagesTable;
use App\Http\Models\Mysql\StyleColourTable;
use App\Http\Models\Mysql\StyleSizeTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\T17Table;
use App\Http\Repository\LogRepository;
use Illuminate\Support\Facades\DB;

class ExportService
{
    public function search($param)
    {
        $conn = (new ExportOrderTable());
        if($param['number'] ?? ""){
            if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                $conn = $conn->where('number', 'like', $param['number']."%");
            }else{
                $conn = $conn->where('number', 'like', "%".$param['number']."%");
            }
        }
        if($param['type_no'] ?? "" || $param['type_name'] ?? ""){
            $productConn = (new ExportOrderProductTable());
            if($param['type_no'] ?? ""){
                if(preg_match("/^[a-zA-Z]/is", $param['type_no'])){
                    $productConn = $productConn->where('product_number', "like", $param['type_no']."%");
                }else{
                    $productConn = $productConn->where('product_number', "like", "%".$param['type_no']."%");
                }
            }
            if($param['type_name'] ?? ""){
                $productConn = $productConn->where('product', 'like', '%'.$param['type_name'].'%');
            }
            $productList = $productConn->get(['export_order_id'])->toArray();
            if(empty($productList)){
                return ['data' => [], 'total' => 0];
            }else{
                $ids = array_column($productList, 'export_order_id');
                $conn = $conn->whereIn('id', $ids);
            }
        }
        if($param['creator'] ?? ""){
            $conn = $conn->where('creator', 'like', "%".$param['creator']."%");
        }
        if(isset($param['state']) && $param['state'] != ""){
            $conn = $conn->where('state', (Int)$param['state']);
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        $ids = array_column($res['data'], 'id');
        //获取款号
        $exportOrderProductList = (new ExportOrderProductTable())->whereIn('export_order_id', $ids)->get(['export_order_id', 'product_number', 'product'])->toArray();
        $exportOrderProductMap = [];
        foreach ($exportOrderProductList as $item){
            $exportOrderProductMap[$item['export_order_id']][] = $item;
        }
        foreach ($res['data'] as &$item){
            $item['delivery_date'] = !empty($item['delivery_date']) ? date('Y-m-d', $item['delivery_date']+1512460800) : "";
            $item['creation_time'] = !empty($item['creation_time']) ? date('Y-m-d', $item['creation_time']+1512460800) : "";
            $item['export_order_product'] = $exportOrderProductMap[$item['id']] ?? [];
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function searchCount($param)
    {
        $conn = (new ExportOrderTable())->select(['id', 'number', 'creator', 'creation_time']);
        if(isset($param['state']) && $param['state'] != ""){
            $conn = $conn->where('state', (Int)$param['state']);
        }
        if($param['number'] ?? ""){
            if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                $conn = $conn->where('number', 'like', $param['number']."%");
            }else{
                $conn = $conn->where('number', 'like', "%".$param['number']."%");
            }
        }
        $productIds = [];
        if(($param['type_no'] ?? "") || ($param['type_name'] ?? "")){
            $productConn = (new ExportOrderProductTable());
            if($param['type_no'] ?? ""){
                if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                    $productConn = $productConn->where('product_number', 'like', $param['type_no']."%");
                }else{
                    $productConn = $productConn->where('product_number', 'like', "%".$param['type_no']."%");
                }
            }
            if($param['type_name'] ?? ""){
                $productConn = $productConn->where('product', 'like', '%'.$param['type_name'].'%');
            }
            $productList = $productConn->get(['id', 'export_order_id'])->toArray();
            if(empty($productList)){
                return ['data' => [], 'total' => 0];
            }else{
                $ids = array_column($productList, 'export_order_id');
                $productIds = array_column($productList, 'id');
                $conn = $conn->whereIn('id', $ids);
            }
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        if(empty($res['data'])){
            return ['data' => [], 'total' => 0];
        }
        $ids = array_column($res['data'], 'id');
        $exportOrderMap = [];
        foreach ($res['data'] as $item){
            $item['customer_purchase_order_date'] = date('Y-m-d', $item['creation_time']+1512460800);
            $exportOrderMap[$item['id']] = $item;
        }
        //款号
        $exportOrderProductList = (new ExportOrderProductTable())->whereIn('export_order_id', $ids)->where(function($query) use($productIds){
            if(!empty($productIds)){
               $query->whereIn('id', $productIds);
            }
        })->get()->toArray();
        $exportOrderProductMap = array_column($exportOrderProductList, null, 'id');
        $exportOrderProductIds = array_column($exportOrderProductList, 'id');
        $styleIds = array_column($exportOrderProductList, 'product_id');
        //item
        $exportOrderItemList = (new ExportOrderItemTable())->whereIn('export_order_id', $ids)->get()->toArray();
        $exportOrderItemMap = array_column($exportOrderItemList, null, 'id');
        //获取款号信息
        $styleList = (new StyleTable())->whereIn('id', $styleIds)->get(['id', 'f8_id', 'f8_short', 'f9_id', 'f9_short', 'f10_id', 'f10_short', 'f11_id', 'f11_short'])->toArray();
        $styleMap = array_column($styleList, null, 'id');
        //颜色
        $exportOrderProductColourList = (new ExportOrderProductColourTable())->whereIn('export_order_id', $ids)->whereIn('export_order_product_id', $exportOrderProductIds)
            ->get()->toArray();
        $exportOrderProductColourMap = array_column($exportOrderProductColourList, null, 'id');
        //数量
        $exportOrderCountList = (new ExportOrderCountTable())->whereIn('export_order_id', $ids)->whereIn('export_order_product_id', $exportOrderProductIds)
            ->orderBy('export_order_id', 'desc')->orderBy('export_order_product_id', 'desc')->orderBy('export_order_product_colour_id', 'desc')->get()->toArray();
        //已经被加工单使用的
        $productSubcontractItemDetailCountList = (new ProductSubcontractItemDetailCountTable())->whereIn('order_count_id', array_column($exportOrderCountList, 'id'))
            ->get(['order_count_id'])->toArray();
        $orderCountIds = array_column($productSubcontractItemDetailCountList, 'order_count_id');
        //尺码
        $exportOrderProductSizeList = (new ExportOrderProductSizeTable())->whereIn('export_order_id', $ids)->whereIn('export_order_product_id', $exportOrderProductIds)
            ->get(['id', 'size', 'size_id', 'size_number'])->toArray();
        $exportOrderProductSizeMap = array_column($exportOrderProductSizeList, null, 'id');
        $data = [];
        foreach ($exportOrderCountList as $item){
            //排查：1、已使用的订单数量 2、下单数为0
            if(in_array($item['id'], $orderCountIds) || empty($item['count'])){
                continue;
            }
            $item['export_order_number'] = $exportOrderMap[$item['export_order_id']]['number'];
            $item['creator'] = $exportOrderMap[$item['export_order_id']]['creator'];
            $item['customer_purchase_order_date'] = $exportOrderMap[$item['export_order_id']]['customer_purchase_order_date'];
            $item['order_product'] = $exportOrderProductMap[$item['export_order_product_id']];
            $item['order_item'] = $exportOrderItemMap[$item['export_order_item_id']];
            $item['order_item']['customer_purchase_order_date'] = date('Y-m-d', strtotime("2017-12-06"."+ {$item['order_item']['customer_purchase_order_date']} days"));
            $item['order_colour'] = $exportOrderProductColourMap[$item['export_order_product_colour_id']];
            $item['order_size'] = $exportOrderProductSizeMap[$item['export_order_product_size_id']];
            $item['style'] = $styleMap[$item['order_product']['product_id']];
            $data[] = $item;
        }
        return ['data' => $data, 'total' => count($data)];
    }

    public function searchStyle($param)
    {
        $conn = (new StyleTable())->select(['id', 'number', 'name', 't17_id', 'product_category_id', 'product_category', 'detail_category_id', 'detail_category'])
            ->where('state', 3)->where('approval_state', '<>', 4);
        if($param['number'] ?? ""){
            if(preg_match("/^[a-zA-Z]/is", $param['number'])){
                $conn = $conn->where('number', 'like', $param['number']."%");
            }else{
                $conn = $conn->where('number', 'like', "%".$param['number']."%");
            }
        }
        if($param['numbers'] ?? []){
            $conn = $conn->whereIn('number', $param['numbers']);
        }
        if($param['name'] ?? ""){
            $conn = $conn->where('name', 'like', "%".$param['name']."%");
        }
        if($param['t17_number'] ?? ""){
            $t17Obj = (new T17Table())->where('number', $param['t17_number'])->first();
            if(empty($t17Obj)){
                return ['data' => [], 'total' => 0];
            }
            $conn = $conn->where('t17_id', $t17Obj->id);
        }
        if($param['is_subject'] ?? ""){
            $subjects = array_column(config("scm.subject"), 'brand_id', 'is_subject');
            $conn = $conn->where('brand_id', $subjects[$param['is_subject']]);
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        if(empty($res['data'])){
            return ['data' => [], 'total' => 0];
        }
        $t17Ids = array_column($res['data'], 't17_id');
        $styleIds = array_column($res['data'], 'id');
        $typeNos = array_column($res['data'], 'number');
        //款式图片
        $styleImages = (new SsyStyleImagesTable())->whereIn('type_no', $typeNos)->get(['type_no', 'thumb_images'])->toArray();
        $styleImagesMap = array_column($styleImages, 'thumb_images', 'type_no');
        //套装编码
        $t17List = (new T17Table())->whereIn('id', $t17Ids)->get()->toArray();
        $t17Map = array_column($t17List, 'number', 'id');
        //获取对应的颜色
        $styleColourList = (new StyleColourTable())->whereIn('style_id', $styleIds)->get()->toArray();
        $styleColourMap = [];
        foreach ($styleColourList as $item) {
            $styleColourMap[$item['style_id']][] = $item;
        }
        //获取对应的尺码 尺寸表数据
        $newSizeList = (new SsyNewProductsSizeTable())->whereIn('type_no', $typeNos)->get(['type_no', 'plank_house_table_title'])->toArray();
        $newSizeMap = [];
        foreach ($newSizeList as $item){
            $plankHouseTableTitle = json_decode($item['plank_house_table_title'], true);
            foreach ($plankHouseTableTitle['code_list'] ?? [] as $codeObj){
                if($codeObj['is']){
                    $newSizeMap[$item['type_no']][] = [
                        'size' => $codeObj['size_code']['title'],
                        'size_id' => $codeObj['size_code']['id'],
                        'size_number' => $codeObj['size_code']['title'],
                        'count' => '',
                    ];
                }
            }
        }
        //数加尺码
        $styleSizeList = (new StyleSizeTable())->whereIn('style_id', $styleIds)->orderBy('position', 'asc')->get()->toArray();
        $styleSizeMap = [];
        foreach ($styleSizeList as $item){
            $item['count'] = "";
            $styleSizeMap[$item['style_id']][] = $item;
        }
        $data = [];
        foreach ($res['data'] as $item){
            foreach ($styleColourMap[$item['id']] as $colourObj) {
                $item['img'] = $styleImagesMap[$item['number']] ?? "";
                $item['style_colour'] = $colourObj;
                $item['style_size'] = $newSizeMap[$item['number']] ?? $styleSizeMap[$item['id']];
                $item['t17_number'] = $t17Map[$item['t17_id']] ?? "";
                $data[] = $item;
            }
        }
        return ['data' => $data, 'total' => $res['total']];
    }

    public function lock($id, $state)
    {
        $exportOrderObj = (new ExportOrderTable())->where('id', $id)->first();
        //写入操作日志
        LogRepository::setOperateLog(auth()->guard("api")->user()->name, $state==1?"锁定":"解锁", $exportOrderObj->number, 1);
        return (new ExportOrderTable())->updateData($id, ['state' => $state]);
    }

    public function del($id)
    {
        $orderObj = (new ExportOrderTable())->where('id', $id)->first()->toArray();
        if($orderObj['state'] == 1){
            return ['code' => -1, 'msg' => '删除失败：当前单据已锁定'];
        }
        $exist = (new ProductSubcontractItemTable())->where('export_order_number', $orderObj['number'])->exists();
        if($exist){
            return ['code' => -1, 'msg' => '删除失败：该单据已被依赖'];
        }
        (new ExportOrderTable())->deleteData($id);//运营订单主表
        (new ExportOrderProductTable())->deleteDataWhere(['export_order_id' => $id]);//运营订单--款号表
        (new ExportOrderProductColourTable())->deleteDataWhere(['export_order_id' => $id]);//运营订单--款号颜色表
        (new ExportOrderColourPositionTable())->deleteDataWhere(['export_order_id' => $id]);//运营订单--款号颜色序列表
        (new ExportOrderProductSizeTable())->deleteDataWhere(['export_order_id' => $id]);//运营订单--款号尺码表
        (new ExportOrderSizePositionTable())->deleteDataWhere(['export_order_id' => $id]);//运营订单--款号尺码序列表
        (new ExportOrderCountTable())->deleteDataWhere(['export_order_id' => $id]);//运营订单--下单数表
        (new ExportOrderItemTable())->deleteDataWhere(['export_order_id' => $id]);//运营订单--下单、交期、批次表
        //写入操作日志
        $user = auth()->guard("api")->user();
        LogRepository::setOperateLog($user->name, "单据删除", $orderObj['number'], 1);
        return ['code' => 0];
    }

    public function detail($id)
    {
        //运营订单主表
        $orderObj = (new ExportOrderTable())->where('id', $id)->first()->toArray();
        $orderObj['delivery_date'] = $orderObj['delivery_date'] ? date('Y-m-d', $orderObj['delivery_date']+1512460800) : "";
        //款号表
        $productList = (new ExportOrderProductTable())->where('export_order_id', $id)->get()->toArray();
        $productMap = array_column($productList, null, 'id');
        //款式图片
        $typeNos = array_column($productList, 'product_number');
        $styleImages = (new SsyStyleImagesTable())->whereIn('type_no', $typeNos)->get(['type_no', 'thumb_images'])->toArray();
        $styleImagesMap = array_column($styleImages, 'thumb_images', 'type_no');
        //尺码序列表
        $sizePositionList = (new ExportOrderSizePositionTable())->where('export_order_id', $id)->orderBy('position', 'asc')->get()->toArray();
        //尺码表
        $productSizeList = (new ExportOrderProductSizeTable())->where('export_order_id', $id)->get()->toArray();
        $productSizeMap = array_column($productSizeList, null, 'id');
        //下单数表
        $countList = (new ExportOrderCountTable())->where('export_order_id', $id)->get()->toArray();
        $countMap = [];
        foreach ($countList as $item){
            $item['product_size'] = $productSizeMap[$item['export_order_product_size_id']] ?? [];
            $item['count'] = $item['count'] ?: "";
            $size = $productSizeMap[$item['export_order_product_size_id']]['size'] ?? "";
            $countMap[$item['export_order_product_id']][$item['export_order_product_colour_id']][$size] = $item;
        }
        //下单、交期、批次表
        $itemList = (new ExportOrderItemTable())->where('export_order_id', $id)->get()->toArray();
        $itemMap = [];
        foreach ($itemList as $item){
            $item['delivery_date'] = $item['delivery_date'] ? date('Y-m-d', $item['delivery_date']+1512460800) : "";
            $item['customer_purchase_order_date'] = $item['customer_purchase_order_date'] ?
                date('Y-m-d', strtotime("2017-12-06"."+ {$item['customer_purchase_order_date']} days")) : "";
            $itemMap[$item['id']] = $item;
        }
        //款号颜色表
        $productColourList = (new ExportOrderProductColourTable())->where('export_order_id', $id)->get()->toArray();
        $productColourMap = array_column($productColourList, null, 'id');
        //颜色序列表--主要明细排列顺序
        $colourPositionList = (new ExportOrderColourPositionTable())->where('export_order_id', $id)->orderBy('position', 'asc')
            ->get(['id', 'position', 'export_order_product_id', 'export_order_item_id', 'export_order_product_colour_id'])->toArray();
        $detailList = [];
        foreach ($colourPositionList as $item){
            $productColourObj = $productColourMap[$item['export_order_product_colour_id']];
            $itemObj = $itemMap[$item['export_order_item_id']];
            $productObj = $productMap[$item['export_order_product_id']];
            $productObj['product_colour'] = $productColourObj;
            $productObj['colour_position'] = $item;
            $productObj['item'] = $itemObj;
            $productObj['count'] = $countMap[$item['export_order_product_id']][$item['export_order_product_colour_id']] ?? [];
            $productObj['img'] = $styleImagesMap[$productObj['product_number']] ?? "";
            $detailList[] = $productObj;
        }
        $orderObj['size_position'] = $sizePositionList;
        $orderObj['detail_list'] = $detailList;
        return $orderObj;
    }

    public function save($param)
    {
        $user = auth()->guard("api")->user();
        list($exportOrder, $detailList, $sizeList, $deleteProductIds) = [
            json_decode($param['export_order'], true),
            json_decode($param['detail_list'], true),
            json_decode($param['size_list'], true),
            json_decode($param['delete_product_ids'], true)
        ];
        try{
            DB::connection("mysql_sj")->beginTransaction();
            //保存主表、item表
            $orderRes = $this->saveExportOrder($exportOrder, $user);
            if($orderRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $orderRes;
            }
            //创建单据
            if(empty($exportOrder['id'])){
                //写入操作日志
                LogRepository::setOperateLog($user->name, "创建单据", $orderRes['number'], 1);
            }
            //删除不需要的款式
            if(!empty($deleteProductIds)){
                $deleteWhere = ['export_order_id' => $orderRes['id'], 'export_order_product_id' => ['in' => $deleteProductIds]];
                (new ExportOrderProductTable())->deleteData($deleteProductIds);//运营订单--款号表
                (new ExportOrderProductColourTable())->deleteDataWhere($deleteWhere);//运营订单--款号颜色表
                (new ExportOrderColourPositionTable())->deleteDataWhere($deleteWhere);//运营订单--款号颜色序列表
                (new ExportOrderProductSizeTable())->deleteDataWhere($deleteWhere);//运营订单--款号尺码表
                (new ExportOrderCountTable())->deleteDataWhere($deleteWhere);//运营订单--下单数表
            }
            //保存尺码序列表
            $sizePositionRes = $this->saveExportOrderSizePosition($sizeList, $orderRes['id']);
            if($sizePositionRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $sizePositionRes;
            }
            //保存款式表、颜色表、颜色序列表、尺码表、count表
            $productRes = $this->saveExportOrderProduct($detailList, $orderRes['id'], $orderRes['export_order_item_id'], $sizePositionRes['size_map']);
            if($productRes['code'] !== 0){
                DB::connection("mysql_sj")->rollBack();
                return $productRes;
            }
            //是否数量配比变更 且 非新建单据
            if($productRes['flag'] && ($exportOrder['id'] ?? "")){
                //写入操作日志
                LogRepository::setOperateLog($user->name, "数量配比变更", $orderRes['number'], 1);
            }
            DB::connection("mysql_sj")->commit();
            return ['code' => 0];
        }catch (\Exception $e){
            DB::connection("mysql_sj")->rollBack();
            return ['code' => -1, 'msg' => "提交失败：".$e->getMessage()];
        }
    }

    public function saveExportOrder($param, $user)
    {
        if($param['id'] ?? ""){
            $data = [
                'delivery_date' => empty($param['delivery_date']) ? 0 : strtotime($param['delivery_date']) - 1512460800,
                'count' => (Int)$param['count'],
                'real_count' => (Int)$param['count'],
                'comment' => $param['comment'],
                'type' => (Int)$param['type']
            ];
            $res = (new ExportOrderTable())->updateData((Int)$param['id'], $data);
            $itemObj = (new ExportOrderItemTable())->where('export_order_id', (Int)$param['id'])->first();
            (new ExportOrderItemTable())->updateData($itemObj->id, ['delivery_date' => $data['delivery_date']]);
            $res['id'] = (Int)$param['id'];
            $res['export_order_item_id'] = $itemObj['id'];
            $res['number'] = $param['number'];
            return $res;
        }else{
            $number2 = (new Number2Table())->first();
            $number2Data = ['head' => date('ym'), 'count' => $number2->head == date('ym') ? $number2->count + 1 : 1];
            DB::connection("mysql_sj")->table("number_2")->update($number2Data);
            $data = [
                'number' => "OE".$number2Data['head'].str_pad($number2Data['count'],3,"0",STR_PAD_LEFT),
                'type' => (Int)$param['type'],
                'source_product_subcontract_id' => 0,
                'source_product_subcontract_number' => "",
                'customer_id' => 0,
                'customer' => '',
                'customer_short' => '',
                'customer_company_id' => 0,
                'customer_contract_number' => '',
                'delivery_date' => empty($param['delivery_date']) ? 0 : strtotime($param['delivery_date']) - 1512460800,
                'count' => (Int)$param['count'],
                'real_count' => (Int)$param['count'],
                'price' => 0,
                'currency_id' => (Int)$param['currency_id'],
                'comment' => $param['comment'],
                'state' => 0,
                'approval_state' => 0,
                'creator_id' => 5,//$user->id, //数加系统 用户查看权限问题，默认用户 5
                'creator' => $user->name,
                'creation_time' => strtotime(date('Y-m-d')) - 1512460800
            ];
            $res = (new ExportOrderTable())->createData($data);
            if($res['code'] === 0){
                $itemData = [
                    'export_order_id' => $res['id'],
                    'customer_purchase_order_number' => date('m-d'),//批次
                    'customer_purchase_order_date' => (strtotime(date('Y-m-d')) - strtotime("2017-12-06"))/(60*60*24),//下单日期 当天
                    'delivery_date' => $data['delivery_date'],//交期
                    'country_id' => 0,
                    'country' => '',
                    'port_id' => 0,
                    'port' => '',
                    'method_id' => 3,
                    'comment' => ''
                ];
                $itemRes = (new ExportOrderItemTable())->createData($itemData);
                if($itemRes['code'] !== 0){
                    return array_merge($res, $itemRes);
                }
                $res['export_order_item_id'] = $itemRes['id'];
                $res['number'] = $data['number'];
            }
            return $res;
        }
    }

    public function saveExportOrderSizePosition($sizeList, $exportOrderId)
    {
        $sizeMap = [];
        foreach ($sizeList as $item){
            if($item['id'] ?? ""){
                $sizeMap[$item['size']] = $item['id'];
                (new ExportOrderSizePositionTable())->updateData((Int)$item['id'], ['position' => (Int)$item['position']]);
            }else{
                $data = [
                    'export_order_id' => $exportOrderId,
                    'position' => (Int)$item['position'],
                    'size' => $item['size']
                ];
                $res = (new ExportOrderSizePositionTable())->createData($data);
                if($res['code'] !== 0){
                    return $res;
                }
                $sizeMap[$data['size']] = $res['id'];
            }
        }
        //把不再序列里面的尺码删除
        (new ExportOrderSizePositionTable())->deleteDataWhere(['export_order_id' => $exportOrderId, 'id' => ['not_in' => array_values($sizeMap)]]);
        return ['code' => 0, 'size_map' => $sizeMap];
    }

    public function saveExportOrderProduct($detailList, $exportOrderId, $exportOrderItemId, $sizeMap)
    {
        $flag = 0;//数量配比异动
        foreach ($detailList as $product){
            $exportOrderProductId = $product['id'] ?? "";
            //创建款式表
            if(empty($exportOrderProductId)){
                $productData = [
                    'export_order_id' => $exportOrderId,
                    'product_id' => (Int)$product['product_id'],
                    'product_number' => $product['product_number'],
                    'product' => $product['product'],
                    'product_category_id' => $product['product_category_id'],
                    'product_category' => $product['product_category'],
                    'product_detail_category_id' => $product['product_detail_category_id'],
                    'product_detail_category' => $product['product_detail_category'],
                    'customer_product_number' => '',
                    't17_id' => $product['t17_id']
                ];
                $res = (new ExportOrderProductTable())->createData($productData);
                if($res['code'] !== 0){
                    return $res;
                }
                $exportOrderProductId = $res['id'];
            }
            //创建颜色表
            $exportOrderProductColourId = $product['product_colour']['id'] ?? "";
            if(empty($exportOrderProductColourId)){
                $productColourData = [
                    'export_order_id' => $exportOrderId,
                    'export_order_product_id' => $exportOrderProductId,
                    'colour_id' => $product['product_colour']['colour_id'],
                    'colour_number' => $product['product_colour']['colour_number'],
                    'colour' => $product['product_colour']['colour'],
                    'colour_value' => $product['product_colour']['colour_value'],
                    'customer_product_colour' => ''
                ];
                $res = (new ExportOrderProductColourTable())->createData($productColourData);
                if($res['code'] !== 0){
                    return $res;
                }
                $exportOrderProductColourId = $res['id'];
            }
            //创建颜色序列表
            $exportOrderColourPositionId = $product['colour_position']['id'] ?? "";
            if(empty($exportOrderColourPositionId)){
                $colourPositionData = [
                    'export_order_id' => $exportOrderId,
                    'position' => (Int)$product['colour_position']['position'],
                    'export_order_item_id' => $exportOrderItemId,
                    'customer_purchase_order_number' => '',
                    'customer_purchase_order_date' => 0,
                    'delivery_date' => 0,
                    'country_id' => 0,
                    'country' => '',
                    'port_id' => 0,
                    'port' => '',
                    'method_id' => 0,
                    'comment' => '',
                    'export_order_product_id' => $exportOrderProductId,
                    'export_order_product_colour_id' => $exportOrderProductColourId
                ];
                $res = (new ExportOrderColourPositionTable())->createData($colourPositionData);
                if($res['code'] !== 0){
                    return $res;
                }
                $exportOrderColourPositionId = $res['id'];
            }
            //处理尺码表、count表
            foreach ($product['count'] as $size => $countObj){
                //创建尺码表
                $exportOrderProductSizeId = $countObj['product_size']['id'] ?? "";
                if(empty($exportOrderProductSizeId)){
                    $productSizeData = [
                        'export_order_id' => $exportOrderId,
                        'export_order_product_id' => $exportOrderProductId,
                        'export_order_size_position_id' => $sizeMap[$size],
                        'size_id' => 0,
                        'size_number' => $countObj['product_size']['size_number'],
                        'size' => $countObj['product_size']['size']
                    ];
                    $res = (new ExportOrderProductSizeTable())->createData($productSizeData);
                    if($res['code'] !== 0){
                        return $res;
                    }
                    $exportOrderProductSizeId = $res['id'];
                }
                //处理count表
                $productCountId = $countObj['id'] ?? "";
                if(empty($productCountId)){
                    $productCountData = [
                        'export_order_id' => $exportOrderId,
                        'export_order_colour_position_id' => $exportOrderColourPositionId,
                        'export_order_item_id' => $exportOrderItemId,
                        'export_order_product_id' => $exportOrderProductId,
                        'export_order_product_colour_id' => $exportOrderProductColourId,
                        'export_order_size_position_id' => $sizeMap[$size],
                        'export_order_product_size_id' => $exportOrderProductSizeId,
                        'source_product_subcontract_item_detail_count_id' => 0,
                        'count' => (Int)($countObj['count'] ?: 0),
                        'price' => 0,
                        'forecasted' => 0,
                        'planned' => 0,
                        'packed' => 0
                    ];
                    $flag = 1;
                    $res = (new ExportOrderCountTable())->createData($productCountData);
                    if($res['code'] !== 0){
                        return $res;
                    }
                }else{
                    $countExist = (new ExportOrderCountTable())->where('id', $productCountId)->first(['count']);
                    if($countExist->count != $countObj['count']){
                        $flag = 1;
                        (new ExportOrderCountTable())->updateData($productCountId, ['count' => (Int)($countObj['count'] ?: 0)]);
                    }
                }
            }
        }
        return ['code' => 0, 'flag' => $flag];
    }
}
